import { Component, OnInit } from '@angular/core';
import { GoodsSelectComponent } from 'src/app/component/goods-select/goods-select.component';
import { ModalController, NavController, AlertController } from '@ionic/angular';
import { AuthService } from 'src/app/services/auth.service';
import { ActivatedRoute, Params } from '@angular/router';
import { Helper } from 'src/app/providers/Helper';
import { NativeService } from 'src/app/providers/NativeService';
import { ShopService } from 'src/app/services/shop.service';
import { ToastService } from 'src/app/providers/toast/toast.service';
import * as constants from 'src/app/providers/Constants'
import * as GOODS_DETAILS from 'src/app/providers/ConstantEN'
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { Storage } from 'src/app/providers/Storage';
import { Utils } from 'src/app/providers/Utils';
@Component({
  selector: 'app-goods-details',
  templateUrl: './goods-details.page.html',
  styleUrls: ['./goods-details.page.scss'],
})
export class GoodsDetailsPage implements OnInit {
  merchCode: string = ''
  commentListFold: any = [];
  sliceIndex = 20;
  slideOpts: any = {
    initialSlide: 1,
    speed: 400,
    // spaceBetween: 12 //px中幻灯片之间的距离。
  };
  shopDetail: any = {
    procModelName: ''
  };
  isDetails: boolean = false;
  headerSlideData: any = [];
  commentList: any = [];
  commentListLength: number = 0;
  shopId: string;
  imageUrl: string;
  procPriceId: string = '';
  storage: any;
  isAddress: boolean = false;
  isChecked: boolean = true;
  isShowGoods: boolean = false;
  isShow: boolean = false;
  topNumber: number = 800;//定位距离
  isDetailImg: boolean = false;
  isStock: string = '';
  procList: any = [];
  isCollect: boolean = false;
  collectId: string = '';
  constructor(private modalController: ModalController, private nav: NavController,
    public navCtrl: NavController,
    private mAuthService: AuthService,
    private alertController: AlertController,
    public activeRoute: ActivatedRoute,
    private mHelper: Helper,
    private statusBar: StatusBar,
    private mDevice: NativeService,
    public service: ShopService,
    private toast: ToastService) {
    this.activeRoute.queryParams.subscribe((params: Params) => {
      if (params.shopInfo != undefined) {
        // console.log('========parms***=',params.shopInfo.merchCode);
        console.log('========parms***1=', params.shopInfo);
        this.shopId = JSON.parse(params.shopInfo).procId;
        this.merchCode = JSON.parse(params.shopInfo).merchCode;
        this.procPriceId = JSON.parse(params.shopInfo).procPriceId;
      }
    });
    this.imageUrl = this.service.getImageUrl();
  }

  ngOnInit() {
    this.getDetail();
  }
  ionViewDidEnter() {

  }
  onBack() {
    this.nav.pop();
  }


  onTtKeFu() {
    let phone = Storage.localStorage.get('userPhone');
    if (phone) {
      this.nav.navigateForward('ttkefu');
    } else {
      this.goLogin();
    }
  }
  goodsSize() {
    // [routerLink]="['/goods-size']" routerLinkActive="router-link-active"
    this.nav.navigateForward('goods-size', {
      queryParams: {
        goosSize: JSON.stringify(this.shopDetail.procSize)
      }
    });
  }
  // buy(type){
  //   console.log(type);
  //   this.presentModal(type);
  // }
  goLogin() {
    this.mHelper.alert("SHow", "Please Login", okBtn => {
      this.nav.navigateForward('login');
    })
  }
  buy(type) {
    let token = Storage.localStorage.get("userPhone");
    if (token) {
      if (!this.isDetails) {
        return;
      }
      console.log(type);
      this.service.getProcStandardsByColor({
        procStandards: this.shopDetail.size,
        merchCode: this.shopDetail.merchCode,
        procName: this.shopDetail.procName,
      }).subscribe(res => {
        console.log(res);
        if (res.retCode == '000000') {
          for (let index = 0; index < res.array.length; index++) {
            if (index == 0) {
              res.array[index].isShow = true;
            } else {
              res.array[index].isShow = false;
            }
          }
          console.log('    res.array', res.array);

          this.presentModal(type, res.array);
        } else if (constants.errCode[res.retCode]) {
          if (constants.errCode[res.retCode] != '0') {
            this.toast.show(constants.errCode[res.retCode]);
          }
        } else if (res.retMsg) {
          this.toast.show(res.retMsg);
        } else {
          this.toast.show("exception service routine");
        }
      })
    } else {
      this.goLogin();
    }
  }
  async presentModal(type, dataColor: any = []) {
    const modal = await this.modalController.create({
      component: GoodsSelectComponent,
      cssClass: 'goods-select',
      showBackdrop: true,
      mode: 'md',
      componentProps: {
        btnType: type,
        // isShow: this.isShow, shopId: this.shopId,
        merchCode: this.merchCode,
        dataColor: dataColor,
        shopDetail: this.shopDetail,
        procPriceId: this.procPriceId,
        procList: this.procList
      }
    });

    await modal.present();
    //监听销毁的事件
    const { data } = await modal.onDidDismiss();

  }

  onCollect() {
    let token = Storage.localStorage.get("userPhone");
    if (token) {
      let data = null;
      if (this.collectId != '') {
        data = {
          collectId: this.collectId,
        }
      } else {
        data = {
          procId: this.shopId,
        }
      }
      this.service.getAddCollect(data).subscribe(res => {
        if (res.retCode == '000000') {
          if (this.collectId == '') {
            this.collectId = res.collectId;
            this.toast.show('Successfully');
          } else {
            this.collectId = '';
          }
        } else if (constants.errCode[res.retCode]) {
          if (constants.errCode[res.retCode] != '0') {
            this.toast.show(constants.errCode[res.retCode]);
          }
        } else if (res.retMsg) {
          this.toast.show(res.retMsg);
        } else {
          this.toast.show("exception service routine");
        }
      }, err => {
        console.log('失败了-------------------' + event);

      });
    } else {
      this.goLogin()
    }

  }
  getDetail() {
    this.service.getProcDetail({ procId: this.shopId }).subscribe(res => {
      // 保存成功返沪上一页，否则弹出提示框
      if (res.retCode == '000000') {
        this.getCommentList();

        this.headerSlideData = this.getHeaderSlideData(res.obj.procImg);
        if (Number(res.obj.procCount) <= 0) {
          this.isStock = GOODS_DETAILS.GOODS_DETAILS.STOCK
        } else {
          this.isStock = GOODS_DETAILS.GOODS_DETAILS.AVAILABLE
        }
        if (res.obj.procDetailImg) {
          this.isDetailImg = true;
          // res.obj.procDetailImg = this.imageUrl + res.obj.procDetailImg;
        } else {
          this.isDetailImg = false;
        }
        this.isDetails = true;
        // res.obj.procImg = res.obj.procImg.split(',')[0]
        this.shopDetail = res.obj
        // this.isCollect = res.obj.collectId==''?false:true;
        this.collectId = res.obj.collectId;
        for (let index = 0; index < res.array.length; index++) {
          if (res.array[index].procId == res.obj.procId) {
            res.array[index].isShow = true;
          } else {
            res.array[index].isShow = false;

          }
          // res.array[index].expressFee = res.obj.expressFee;
          // res.array[index].merchName = res.obj.merchName;
          // if (index == 0) {
          //   res.array[index].isShow = true;
          // }

        }

        this.procList = res.array;
      } else if (constants.errCode[res.retCode]) {
        if (constants.errCode[res.retCode] != '0') {
          this.toast.show(constants.errCode[res.retCode]);
        }
      } else if (res.retMsg) {
        this.toast.show(res.retMsg);
      } else {
        this.toast.show("exception service routine");
      }
    }, err => {
      console.log('失败了-------------------' + event);

    });
  }
  private getHeaderSlideData(data) {
    let arr = data.split(',')
    let obj = [];
    arr.forEach((element, index) => {
      let o = {
        alt: '商品',
        src: this.imageUrl + element,
      }
      obj.push(o);
    });
    return obj;
  }
  strFormatData(str) {
    return Utils.strFormatData(str);
  }

  solaImage(img) {
    return Utils.imageUrl(this.imageUrl, img);
  }

  onClickMore() {
    if (this.commentListFold.length == this.commentList.length) {
      this.toast.show('No More');
      return;
    } else {
      if ((this.commentList.length - this.commentListFold.length) > this.sliceIndex) {
        this.commentListFold = this.commentList.slice(0, this.commentListFold.length + this.sliceIndex);
      } else {
        this.commentListFold = this.commentList.slice(0, this.commentList.length);
      }
    }
  }
  getCommentList() {
    this.service.getCommentList({ procId: this.shopId }).subscribe(res => {
      if (res.retCode == '000000') {
        this.commentList = res.data;
        if (this.commentList.length != 0) {
          this.commentListLength = this.commentList.length;
        }
        if (this.commentListFold.length == 0) {
          if (this.commentList.length < this.sliceIndex) {
            this.commentListFold = this.commentList;
          } else {
            this.commentListFold = this.commentList.slice(0, this.sliceIndex);
          }
        }

      } else if (constants.errCode[res.retCode]) {
        if (constants.errCode[res.retCode] != '0') {
          this.toast.show(constants.errCode[res.retCode]);
        }
      } else if (res.retMsg) {
        this.toast.show(res.retMsg);
      } else {
        this.toast.show("exception service routine");
      }
    }, err => {
      console.log('失败了-------------------' + event);

    });
  }
  AmountOfConversion(num: number) {
    return num / 100;
  }

}
